package com.sky.server.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.BaseException;
import com.sky.exception.DTOIsNullException;
import com.sky.exception.SqlException;
import com.sky.mapper.EmployeeMapper;
import com.sky.pojo.StatusUpdate;
import com.sky.result.PageResult;
import com.sky.server.EmployeeServer;
import com.sky.vo.EmployeeLoginVO;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class EmployeeServerImpl implements EmployeeServer {


    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        // 判断登录
        Optional.ofNullable(employeeLoginDTO.getUsername()).orElseThrow(DTOIsNullException::new);
        Employee employee = employeeMapper.selectEmployeeByName(employeeLoginDTO.getUsername());
        if (employee == null) {
            log.info("用户不存在");
            throw new BaseException("用户名或密码错误");
        }

        Optional.ofNullable(employeeLoginDTO.getPassword()).orElseThrow(DTOIsNullException::new);
        String md5Password = DigestUtil.md5Hex(employeeLoginDTO.getPassword());
        if (!Objects.equals(md5Password, employee.getPassword())) {
            log.info("密码错误");
            throw new BaseException("用户名或密码错误");
        }

        // 生成token
        StpUtil.login(employee.getId());
        String token = StpUtil.getTokenValue();

        EmployeeLoginVO employeeLoginVO = new EmployeeLoginVO();
        employeeLoginVO.setId(employee.getId());
        employeeLoginVO.setToken(token);
        employeeLoginVO.setUserName(employee.getUsername());
        employeeLoginVO.setName(employee.getName());

        return employeeLoginVO;
    }

    // 添加员工
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        // 补充字段值
        Employee employee = new Employee();
        BeanUtil.copyProperties(employeeDTO, employee);
        String md5Password = DigestUtil.md5Hex("123456");
        employee.setPassword(md5Password);
        employee.setStatus(0);
        employeeMapper.addEmployee(employee);
    }

    @Override
    public Employee selectEmployeeById(Long id) {
        return employeeMapper.selectEmployeeById(id);
    }

    @Override
    public void updateEmployeeById(EmployeeDTO employeeDTO) {
        try {
            employeeMapper.updateEmployeeById(employeeDTO);
        } catch (Exception e) {
            throw new SqlException("修改sql错误");
        }
    }

    @Override
    public PageResult pageEmployee(EmployeePageQueryDTO employeePageQueryDTO) {
        // 对于分页推荐使用流，可以将查到的数据塞入缓存，减少io次数
        Integer count = employeeMapper.count();
        List<Employee> employeeList = employeeMapper.selectEmployeePage(employeePageQueryDTO);
        log.info("employee={}", employeeList);
        List<Employee> records = employeeList.stream().skip((employeePageQueryDTO.getPage() - 1) * employeePageQueryDTO.getPageSize()).limit(employeePageQueryDTO.getPageSize()).collect(Collectors.toList());

        PageResult pageResult = new PageResult();
        pageResult.setRecords(records);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public void status(Integer status, Long id) {
        StatusUpdate statusUpdate = new StatusUpdate();
        statusUpdate.setStatus(status);
        statusUpdate.setId(id);
        try {
            employeeMapper.status(statusUpdate);
        } catch (Exception e) {
            throw new SqlException("状态修改错误");
        }
    }

    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        // 如果密码验证成功就
        // 获取当前用户的id
        String tokenValue = StpUtil.getTokenValue();
        // todo 解析用astoken 解析jwt获取用户id


        passwordEditDTO.setNewPassword(DigestUtil.md5Hex(passwordEditDTO.getNewPassword()));
        employeeMapper.editPassword(passwordEditDTO);
    }
}
